﻿Imports System.Windows.Controls.Primitives

' Based on http://blog.fossmo.net/post/How-to-create-an-attached-property-in-WPF-using-a-ComboBox.aspx
Public Class SelectionBehavior
  Public Shared SelectionChangedProperty As DependencyProperty = _
  DependencyProperty.RegisterAttached("SelectionChanged", _
                                      GetType(ICommand), _
                                      GetType(SelectionBehavior), _
                                      New UIPropertyMetadata(AddressOf SelectionBehavior.SelectedItemChanged))

  Public Shared Sub SetSelectionChanged(ByVal target As DependencyObject, ByVal value As ICommand)
    target.SetValue(SelectionBehavior.SelectionChangedProperty, value)
  End Sub

  Private Shared Sub SelectedItemChanged(ByVal target As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
    Dim element As Selector = TryCast(target, Selector)
    If element Is Nothing Then
      Throw New InvalidOperationException("This behavior can be attached to Selector item only.")
    End If
    If (e.NewValue IsNot Nothing) AndAlso (e.OldValue Is Nothing) Then
      AddHandler element.SelectionChanged, AddressOf SelectionChanged
    ElseIf (e.NewValue Is Nothing) AndAlso (e.OldValue IsNot Nothing) Then
      RemoveHandler element.SelectionChanged, AddressOf SelectionChanged

    End If
  End Sub

  Private Shared Sub SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
    Dim element As UIElement = DirectCast(sender, UIElement)
    Dim command As ICommand = DirectCast(element.GetValue(SelectionBehavior.SelectionChangedProperty), ICommand)
    command.Execute(DirectCast(sender, Selector).SelectedValue)
  End Sub

End Class
